
import time
from app.config import config
from app.logger import logger
from app.agent.manus import Manus
from app.flow.flow_factory import FlowFactory, FlowType
import asyncio

async def run_flow():
    logger.info(f"Environment mode: {config.env.mode}")
    
    chatbot = await Manus.create()
    agents = {
        "chatbot": chatbot,
    }

    prompt = input("\n💬Enter a prompt (Ctrl+C to exit): ")
    if not prompt.strip():
        logger.warning("Empty prompt. Exiting...")

    flow = FlowFactory.create_flow(
        flow_type = FlowType.PLANNING,
        agents = agents
    )

    logger.warning(f"💬Running agent with prompt: {prompt}")

    try:
        start_time = time.time()
        result = await asyncio.wait_for(
            flow.execute(prompt),
            timeout=3600  # 1小时超时
        )

        elapsed_time = time.time() - start_time
        logger.info(f"Request processed in {elapsed_time:.2f} seconds")
        logger.info(result)
    except asyncio.TimeoutError:
        logger.error("Request timed out after 1 hour.")
        logger.info(
            "Operation terminated due to timeout. Please try a simpler request."
        )
    except asyncio.CancelledError:
        logger.info("Task cancelled. Cleaning up...")
    except KeyboardInterrupt:
        logger.info("Keyboard interrupt received. Cleaning up...")
    except Exception as e:
        logger.error(f"Error: {e}")
    finally:
        logger.info("Cleaning up resources...")
        for agent in agents.values():
            await agent.cleanup()

if __name__ == "__main__":
    try:
        asyncio.run(run_flow())
    except KeyboardInterrupt:
        logger.info("Program terminated by user.")
    except Exception as e:
        logger.error(f"Unexpected error: {e}")
    finally:
        logger.info("Program exited.")